package com.net.xpay.common.service.impl;

import com.net.xpay.common.domain.operator.OperatorUser;
import com.net.xpay.common.enums.user.SecurityStatus;
import com.net.xpay.common.model.RegisterOperatorUserModel;
import com.net.xpay.common.validator.RegisterOperatorUserValidator;
import com.net.xpay.common.manager.operator.OperatorUserManager;
import com.net.xpay.common.service.OperatorUserService;
import org.mindrot.jbcrypt.BCrypt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

@Service
public class OperatorUserServiceImpl implements OperatorUserService {

    @Autowired
    private OperatorUserManager operatorUserManager;

    @Autowired
    private RegisterOperatorUserValidator registerOperatorUserValidator;

    @Override
    public void registerOperatorUser(RegisterOperatorUserModel registerModel) {
        registerOperatorUserValidator.validateRegisterOperatorUser(registerModel);

        OperatorUser operatorUser = createOperatorUser(registerModel);
        operatorUserManager.save(operatorUser);
    }

    private OperatorUser createOperatorUser(RegisterOperatorUserModel registerModel) {
        OperatorUser operatorUser = new OperatorUser();
        operatorUser.setMobile(registerModel.getMobile());

        operatorUser.setRegisterTime(LocalDateTime.now());
        operatorUser.setRegisterIp(registerModel.getIp());
        operatorUser.setLastLoginTime(LocalDateTime.now());
        operatorUser.setLastLoginClient(registerModel.getClientFrom());
        operatorUser.setLastLoginIp(registerModel.getIp());
        operatorUser.setLoginCount(0L);
        operatorUser.setSecurityStatus(SecurityStatus.NORMAL);
        operatorUser.setErrorCount(0);
        //需要特殊处理的字段
        setOperatorUserPassword(operatorUser, registerModel.getPassword());

        return operatorUser;
    }

    private void setOperatorUserPassword(OperatorUser operatorUser, String password) {
        //使用BCrypt加密不需要保存salt,hash值包含了salt的信息
        String crypt = BCrypt.hashpw(password, BCrypt.gensalt());
        operatorUser.setPassword(crypt);
    }
}
